<?php

define("YES", "<span class='text-success'>YES</span>");
define("NO", "<span class='text-danger'>NO</span>");
define("ICON", "<span class='icon'>2</span>&nbsp;");
function openConnection()
{
}

function closeConnection()
{
}
/**
 * 检测 PHP 设置参数
 */
function checkCfgVar($varName)
{
    switch ($res = get_cfg_var($varName)) {
        case 0:
            return NO;
            break;
        case 1:
            return YES;
            break;
        default:
            return $res;
            break;
    }
}
/**
 * 检测 PHP 函数支持
 */
function checkFunction($funName)
{
    return (false !== function_exists($funName)) ? YES : NO;
}
class CommonUtils
{
    public static function input($name, $defaultValue = '')
    {
        if (isset($_REQUEST[$name])) {
            return $_REQUEST[$name];
        }
        $data = [];
        $content = file_get_contents('php://input');
        if ($content) {
            $httpAccept = $_SERVER['HTTP_ACCEPT'];
            if (false !== strpos($httpAccept, 'json')) {
                // Ajax 方式 Post 提交，按照 {key1:val1,key2:val2} 的方式进行编码
                $data = (array) json_decode($content, true);
            } else if (false !== strpos($httpAccept, 'x-www-form-urlencoded')) {
                // 浏览器原生 Post 提交，按照 key1=val1&key2=val2 的方式进行编码
                parse_str($content, $data);
            }
        }
        if (isset($data[$name])) {
            return $data[$name];
        }
        return $defaultValue;
    }
    public static function stdmessage($status, $message, $data = null, $code = 200)
    {
        return ['status' => $status, 'message' => $message, 'data' => $data, 'code' => $code];
    }
    public static function outputJson($data)
    {
        header('Content-type:text/json');
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit;
    }
    public static function formatBytes($size, $digits = 2)
    {
        if (!$size) {
            return $size;
        }
        $base = 1024;
        $unit = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
        // return round($size / pow($base, ($i = floor(log($size, $base)))), 2) . ' ' . $unit[$i];
        $i = floor(log($size, $base));
        $n = count($unit);
        if ($i >= $n) {
            $i = $n - 1;
        }
        return round($size / pow($base, $i), $digits) . ' ' . $unit[$i];
    }

    /**
     * 返回服务器 IP
     * 参考：SERVER_NAME 和 HTTP_HOST 的区别 (http://blog.sina.com.cn/s/blog_6d96d3160100q39x.html)
     * @version 1.0 2017-10-13 Added.
     */
    public static function getHostIP()
    {
        //return $_SERVER['HTTP_HOST']; // 有服务器域名则优先返回域名，否则返回服务器 ip
        return gethostbyname($_SERVER['SERVER_NAME']); // 返回服务器IP
    }
}
